package to52.android.adapters;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import to52.android.screens.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.androidplot.series.XYSeries;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

import fr.utbm.Patient;
import fr.utbm.Sensor;
import fr.utbm.SensorValue;

public class CapteurDetailsAdapter extends BaseAdapter {
	
	private static class ViewHolder {
		XYPlot mySimpleXYPlot;
		TextView plotLegend;
		Button btnPeriod;
    }
	
    private Patient patient;		
    private Sensor capteur;
	private Context mContext;
    private LayoutInflater mInflater;
    private ViewHolder holder;
	
    public int getCount() {
        return 1;
    }

    public Object getItem(int position) {
        return null; //propertiesDetails.get(position);
    }

    public long getItemId(int position) {
        return position;
    }
    
    
    public CapteurDetailsAdapter(Context c, Patient patient, Sensor capteur) {
        mContext = c;
        mInflater = LayoutInflater.from(mContext);
        this.patient = patient;
        this.capteur = capteur;
    }

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.plot, null);

            holder = new ViewHolder();
            holder.mySimpleXYPlot = (XYPlot) convertView.findViewById(R.id.mySimpleXYPlot);
            holder.plotLegend = (TextView)convertView.findViewById(R.id.plotLegend);
            holder.btnPeriod = (Button)convertView.findViewById(R.id.btnPeriod);
            
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        /* remplissage de la vue en fonction du capteur */
        
        holder.mySimpleXYPlot.setTitle("");
        
        // Create two arrays of y-values to plot:
        List<SensorValue> svl = capteur.getValues();
        Number[] values       = new Number[svl.size()];
        Number[] timestamps   = new Number[svl.size()];

        for(int i=0; i<svl.size(); ++i) {
        	values[i]     = svl.get(i).getValue();
        	timestamps[i] = svl.get(i).getDate().getTime().getTime();
        }
        
        // Turn the above arrays into XYSeries:
        XYSeries series1 = new SimpleXYSeries(
        		Arrays.asList(timestamps),
        		Arrays.asList(values),   // Y_VALS_ONLY means use the element index as the x value
                capteur.getType().getLabel());                             // Set the display title of the series
 
 
        // Create a formatter to use for drawing a series using LineAndPointRenderer:
        LineAndPointFormatter series1Format = new LineAndPointFormatter(
                Color.rgb(0, 200, 0),                   // line color
                Color.rgb(0, 100, 0),                   // point color
                null);              // fill color (optional)
 
        /* 
         * MINI
         */
        Number[] valuesMINI       = new Number[2];
        Number[] timestampsMINI   = new Number[2];
        
        valuesMINI[0] = capteur.getType().getMin();
        valuesMINI[1] = capteur.getType().getMin();
        
        timestampsMINI[0] = timestamps[0];
        timestampsMINI[1] = timestamps[timestamps.length - 1];
        
        XYSeries seriesMINI = new SimpleXYSeries(
        		Arrays.asList(timestampsMINI),
        		Arrays.asList(valuesMINI), 
                capteur.getType().getLabel() + " minimum");    
 
        LineAndPointFormatter seriesMINIFormat = new LineAndPointFormatter(
                Color.rgb(0, 0, 200),       
                Color.rgb(0, 0, 80),      
                null);  
        
        /*
         * MAXI
         */
        Number[] valuesMAXI       = new Number[2];
        Number[] timestampsMAXI   = new Number[2];
        
        valuesMAXI[0] = capteur.getType().getMax();
        valuesMAXI[1] = capteur.getType().getMax();
        
        timestampsMAXI[0] = timestamps[0];
        timestampsMAXI[1] = timestamps[timestamps.length - 1];
        
        XYSeries seriesMAXI = new SimpleXYSeries(
        		Arrays.asList(timestampsMAXI),
        		Arrays.asList(valuesMAXI), 
                capteur.getType().getLabel() + " maximum");    
 
        LineAndPointFormatter seriesMAXIFormat = new LineAndPointFormatter(
                Color.rgb(0, 0, 200),       
                Color.rgb(0, 0, 80),      
                null);  
        
        
        holder.mySimpleXYPlot.addSeries(series1, series1Format);
        holder.mySimpleXYPlot.addSeries(seriesMINI, seriesMINIFormat);
        holder.mySimpleXYPlot.addSeries(seriesMAXI, seriesMAXIFormat);
 
 
        // draw a domain tick for each year:
        holder.mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, timestamps.length);
 
        // customize our domain/range labels
        holder.mySimpleXYPlot.setDomainLabel("Date");
        holder.mySimpleXYPlot.setRangeLabel(capteur.getType().getUnite());
        
        holder.mySimpleXYPlot.setDomainValueFormat(new MyDateFormat());
        
        
        // By default, AndroidPlot displays developer guides to aid in laying out your plot.
        // To get rid of them call disableAllMarkup():
        holder.mySimpleXYPlot.disableAllMarkup();
        
        holder.plotLegend.setText(capteur.getType().getLabel() +  " de " + patient.getName());	// à voir avec le capteur getname
        
        /* fin remplissage */
        
        
        // action sur le bouton periode
        holder.btnPeriod.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        final CharSequence[] items = {"Aujourd'hui", "Cette semaine", "Ce mois"};

		        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		        builder.setTitle("Période à afficher");
		        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int item) {
		                //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
		            }
		        });
		        builder.create().show();
			}
		});
		
        
        return convertView;
	}

	
	// http://androidplot.com/wiki/Plotting_Against_Time
    private class MyDateFormat extends Format {
    	 
		private static final long serialVersionUID = 1L;
		
		// create a simple date format that draws on the year portion of our timestamp.
        // see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
        // for a full description of SimpleDateFormat.
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

        @Override
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            long timestamp = ((Number) obj).longValue();
            Date date = new Date(timestamp);
            return dateFormat.format(date, toAppendTo, pos);
        }

        @Override
        public Object parseObject(String source, ParsePosition pos) {
            return null;

        }
    }
    
}
